<template>
    
    <div class="image-container">
    <el-card class="box-card">
      <div slot="header">
       <breadcrump>素材管理</breadcrump>
      </div>
      <div style="padding-bottom: 20px;">
        <el-radio-group v-model="isCollected" size="mini" @change="hCollect">
          <el-radio-button :label="false">全部</el-radio-button>
          <el-radio-button :label="true">收藏</el-radio-button>
        </el-radio-group>
        <el-button
         @click="dialogVisible=true"
         type="success" size="mini" style="float:right">上传图片素材          </el-button>
      </div>
      <!-- 素材列表 -->
    <el-row :gutter="10">
        <el-col  class="img_item" :xs="12" :sm="6" :md="6" :lg="4" v-for="i in images" :key="i.id">
          <el-image
            style="height: 180px;width: 180px"
            :src="i.url"
            fit="cover"
          ></el-image>
          <div class="option" v-show='!isCollected'>
            <span class="el-icon-star-off" @click="hSwitchCollect(i)" :class="{'red':i.is_collected}"></span>
            <span class="el-icon-delete" @click="hDelete(i.id)"></span>
          </div> 
        </el-col>
        
    </el-row>
      <!-- /素材列表 -->
    </el-card>
    <el-pagination
              v-show="total_count>10"
              
               style="margin-top:10px;"
              
               layout="prev, pager, next"
               @current-change="hPageChange"
               :total="total_count">
</el-pagination>

<!-- 上传图片文件的对话框 -->
    <el-dialog
      title="提示"
      :append-to-body="true"
      :visible.sync="dialogVisible"
      >
      <!--
        action：上传地址
        show-file-list:false，不需要显示已上传的文件列表
        on-success： 上传成功之后的回调函数
        before-upload: 上传之前对文件进行检测
        name: 设置上传的文件参数名，要与后端接口中的要求一致。
      -->

      <el-upload
        class="avatar-uploader"
        action="http://ttapi.research.itcast.cn/mp/v1_0/user/images"
        :headers="h"
        :on-success="hUploadSuccess"
        name="image"
        :show-file-list="false"
        :before-upload="beforeAvatarUpload">
        <!-- 如果当前有预览地址就说明图片上传成功了。 -->
        <el-img v-if="imgSrc" :src="imgSrc" @load="hImageLoad" class="avatar" />
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>

    </el-dialog>
    </div>
     
</template>

<script>
import axios from 'axios'
export default {
  
  name: 'image',
  components: {},
  props: {},
  data () {
    return {
      dialogVisible:false,// 上传素材图片的对话框
      radio1: '全部',
      images:[],
      total_count:0 ,//查询的总数量
      curPage:1,//当前查询第几页
      isCollected:false,
      imgSrc: null,
      h:{
                      Authorization:`Bearer `+localStorage.getItem('tokenInfo')
                  },
    }
  },
  computed: {},
  watch: {},
  created () {
      this.loadImages()
  },
  mounted () {},
  methods: {
    hSwitchCollect(img){
      // 1.调用接口
      // 2.更新视图
      const token = localStorage.getItem('tokenInfo')
      const { id, is_collected: isCollected } =img
      console.log(id,isCollected);
      axios({
        method:'put',
        url:'http://ttapi.research.itcast.cn/mp/v1_0/user/images/'+id,
        headers:{
          Authorization:`Bearer ${token}`
        },
        data:{
          collect:!isCollected
        }
      }).then(res=>{
        this.$message.success('操作成功')
        this.loadImages()
      }).catch(err=>{
        console.log(err);
      })

    },
    hImageLoad(){
      //表示图片加载完成，此时可以正常显示
      console.log('图片加载完成')
      setTimeout(()=>{
        this.imageUrl=''
        this.dialogVisible=false // 关闭对话框
      },2000)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    // 如果上传成功，则会把响应结果传给res
    hUploadSuccess (res) {
      console.log(res)
      // 保存上传成功之后的图片地址
      this.imgSrc = res.data.url
      this.$message.success('上传素材成功')
      this.loadImages()
    },
      hDelete(id){
          this.$confirm('你确定要删除吗')
      .then(()=>{
         
          const token = localStorage.getItem('tokenInfo')
          axios({
                  method:'delete',
                  url:`http://ttapi.research.itcast.cn/mp/v1_0/user/images/${id}`,
                  headers:{
                      Authorization:`Bearer ${token}`
                  }
              }).then(res=>{
                console.log(res);
                  this.$message({
                      message:'删除成功',
                      type:'success'
                      
                  })
                  // 3.根据接口的反馈信息做后续处理
                // 如果这个操作不报错误，则可以认为是删除成功
                // 下面更新页面，有俩种方案
                // （1）再做一次查询 this.hQuery() 这个更加严谨，数据是从后端再次请求来的
                // （2）不做查询，直接删除当前这一行数据 this.articles.splice(index,1)
                  this.loadImages()
              }).catch(err=>{
                  this.$message({
                      message:'删除失败，目前只能删除草稿',
                      type:'error'
                  })
              })
                
      }).catch(()=>{

      })
          
      },
loadImages(){
    const token = localStorage.getItem('tokenInfo')
    axios({
        method:'get',
        url:'http://ttapi.research.itcast.cn/mp/v1_0/user/images',
        headers:{
            Authorization:`Bearer ${token}`
        },
        params:{
            per_page:10,
            collect:this.isCollected,
            page:this.curPage
        }
    }).then(res=>{
        this.images = res.data.data.results
        this.total_count = res.data.data.total_count
        console.log('素材',res);
    })
},
hPageChange(curPage){
    console.log(curPage)
    this.curPage=curPage
    this.loadImages()
},
hCollect(){
    console.log('1111111');
    this.curPage=1
    this.loadImages()
}
  }
}
</script>

<style lang="less" scoped>
  .img_item {
    position: relative;
    box-sizing: border-box;
  }
  .option {
    position: absolute;
    left: 5px;
    right:5px;
    bottom: 5px;
    height: 30px;
    line-height: 30px;
    background: rgba(0, 0, 0, 0.3);
    text-align: center;
    color: #fff;
    span {
      margin: 0 30px;
      cursor: pointer;
    }
    .red {
        color: red;
    }
  }
.avatar-uploader {
    text-align: center;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.avatar-uploader /deep/ .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
</style>